package com.tyut.musicdreamer.service.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * 请求头清理过滤器
 * 用于清理请求头中的冗余信息，防止请求头过大
 */
@Component
@Slf4j
public class HeaderCleanupFilter implements GlobalFilter, Ordered {

    // 需要清理的请求头
    private static final List<String> HEADERS_TO_CLEAN = Arrays.asList(
            "X-Forwarded-Host",
            "X-Forwarded-Port",
            "X-Forwarded-For",
            "X-Forwarded-Proto",
            "Forwarded"
    );

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest originalRequest = exchange.getRequest();
        String path = originalRequest.getPath().toString();
        
        // 记录请求信息
        log.debug("处理请求: {}, 方法: {}", path, originalRequest.getMethod());
        
        // 记录认证相关的请求头
        if (originalRequest.getHeaders().containsKey("Authorization")) {
            log.debug("Authorization头: {}", originalRequest.getHeaders().getFirst("Authorization"));
        } else {
            log.debug("请求中不包含Authorization头");
        }
        
        if (originalRequest.getHeaders().containsKey("satoken")) {
            log.debug("satoken头: {}", originalRequest.getHeaders().getFirst("satoken"));
        } else {
            log.debug("请求中不包含satoken头");
        }
        
        // 创建一个新的请求构建器
        ServerHttpRequest.Builder requestBuilder = originalRequest.mutate();
        
        // 清理指定的请求头
        boolean headersChanged = false;
        for (String header : HEADERS_TO_CLEAN) {
            if (originalRequest.getHeaders().containsKey(header)) {
                requestBuilder.headers(httpHeaders -> httpHeaders.remove(header));
                log.debug("清理请求头: {}", header);
                headersChanged = true;
            }
        }
        
        // 如果请求头没有变化，直接继续过滤器链
        if (!headersChanged) {
            return chain.filter(exchange);
        }
        
        // 使用修改后的请求继续过滤器链
        ServerHttpRequest newRequest = requestBuilder.build();
        log.debug("请求头已清理，继续处理请求: {}", path);
        return chain.filter(exchange.mutate().request(newRequest).build());
    }

    @Override
    public int getOrder() {
        // 在所有其他过滤器之前执行
        return -200;
    }
} 